/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

//BEGIN_INCLUDE(all)
#include <jni.h>
#include <errno.h>

#include <EGL/egl.h>
#include <GLES/gl.h>
#include <GLES/glext.h>

#include <android/sensor.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/configuration.h>
#include <android/keycodes.h>
#include <android_native_app_glue.h>
#include "stdio.h"
#include "math.h"

#include <FreetypeWrapper/FontAtlas.h>
#include <FreetypeWrapper/FTBitmapChar.h>

#include "Util.h"
#include "Global.h"
#include "Game.h"
#include "libpng/png.h"
#include "Font/FontMain.h"
#include "ResourcesManager.h"
#include "EWorld.h"
#include "EMesh.h"

Game *main 				= NULL;
float myAngle 			= 0.0f;
static AAsset* asset 	= NULL;
static AAsset* fontFile = NULL;
FontAtlas *fontAtlas	= NULL;
//FTBitmapFont *fontMain	= NULL;
static GLCallBatcher batcher;
AAssetManager* pngAassetManager = 0;
GLuint tex;
Texture* cubeTexture;
World scene;
double lastTime		= 0.0;
/**
 * Our saved state data.
 */
struct saved_state {
    float angle;
    int32_t x;
    int32_t y;
};

/**
 * Shared state for our app.
 */
struct engine {
    struct android_app* app;

    ASensorManager* sensorManager;
    const ASensor* accelerometerSensor;
    ASensorEventQueue* sensorEventQueue;

    int animating;
    EGLDisplay display;
    EGLSurface surface;
    EGLContext context;
    int32_t width;
    int32_t height;
    struct saved_state state;
};

void glPerspective(float fov,float aspect,float zNear,float zFar) {
		float top, bottom, left, right;
		top 		= zNear * tan(fov* M_PI / 360.0);
		bottom 		= -top;
		left 		= bottom * aspect;
		right 		= top * aspect;
		glFrustumf(left, right, bottom, top, zNear, zFar);
}

void initFreeTP(const void* fontData, off_t fontLen) {

    uint arraySize = 1;
    for (uint i = 0; i < fontMainCharsetSize; ++i)
        arraySize += fontMainCharset[i][1] - fontMainCharset[i][0] + 1;

    wchar_t *letters = new wchar_t[arraySize];
    memset(letters, 0, arraySize * sizeof(wchar_t));

    uint index = 0;
    for (uint i = 0; i < fontMainCharsetSize; ++i) {
        for (uint letter = fontMainCharset[i][0]; letter <= fontMainCharset[i][1]; ++letter) {
            letters[index++] = static_cast<wchar_t>(letter);
        }
    }
    int desiredTextureSize = 2048;
    int maxTextureSize;
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);

    int textureSize;
        if (maxTextureSize < desiredTextureSize)
        	textureSize = maxTextureSize;
        else
        	textureSize = desiredTextureSize;

    fontAtlas = new FontAtlas(&batcher, textureSize, textureSize);
    int fontSize = 64;

    fontAtlas->addFont(fontData, fontLen, fontSize, letters);
    fontAtlas->createAtlas();
    fontAtlas->getFont(0)->smooth = false;
    main->fontMain = fontAtlas->getFont(0);

//    LOGE("\nFont height:          %d", fontAtlas->getFont(0)->getHeight());
//    LOGE("\nFont size:            %d", fontSize);
//    printf("\nFont scale:           %f", globalScale);
//    LOGE("\nDesired texture size: %d", desiredTextureSize);
//    LOGE("\nMax texture size: 	%d", maxTextureSize);
//    LOGE("\nTexture size: 		%d", textureSize);
}

/**
 * Initialize an EGL context for the current display.
 */
static int engine_init_display(struct engine* engine) {
    // initialize OpenGL ES and EGL

    /*
     * Here specify the attributes of the desired configuration.
     * Below, we select an EGLConfig with at least 8 bits per color
     * component compatible with on-screen windows
     */
    const EGLint attribs[] = {
            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
            EGL_BLUE_SIZE, 8,
            EGL_GREEN_SIZE, 8,
            EGL_RED_SIZE, 8,
            EGL_DEPTH_SIZE, 16,   // You need this line for depth buffering to work
            EGL_NONE
    };
    EGLint w, h, dummy, format;
    EGLint numConfigs;
    EGLConfig config;
    EGLSurface surface;
    EGLContext context;

    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    eglInitialize(display, 0, 0);

    /* Here, the application chooses the configuration it desires. In this
     * sample, we have a very simplified selection process, where we pick
     * the first EGLConfig that matches our criteria */
    eglChooseConfig(display, attribs, &config, 1, &numConfigs);

    /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
     * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
     * As soon as we picked a EGLConfig, we can safely reconfigure the
     * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
    eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

    ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);

    surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
    context = eglCreateContext(display, config, NULL, NULL);

    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
        LOGW("Unable to eglMakeCurrent");
        return -1;
    }

    eglQuerySurface(display, surface, EGL_WIDTH, &w);
    eglQuerySurface(display, surface, EGL_HEIGHT, &h);

    engine->display = display;
    engine->context = context;
    engine->surface = surface;
    engine->width = w;
    engine->height = h;
    engine->state.angle = 0;

//	glMatrixMode(GL_PROJECTION);
//	glLoadIdentity();
//	glOrthof(0, w, 0, h, -1, 1);
//
//	glMatrixMode(GL_MODELVIEW);
//	glLoadIdentity();
//	glViewport(0, 0, w, h);
//	glScissor(0, 0, w, h);
//
//	glEnable(GL_BLEND);
//	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//	glEnable(GL_TEXTURE_2D);
//	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
//	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, /*GL_NEAREST*/ GL_LINEAR);
//	glEnableClientState(GL_VERTEX_ARRAY);
//	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//	glDisableClientState(GL_NORMAL_ARRAY);
//	glDisableClientState(GL_COLOR_ARRAY);
//	glShadeModel(GL_SMOOTH);
//	glDisable(GL_DEPTH_TEST);
//
//	glDisable(GL_DITHER);


    // Initialize GL state.
	glEnable(GL_TEXTURE_2D);			//Enable Texture Mapping ( NEW )
	glEnable(GL_DEPTH_TEST); 			//Enables Depth Testing
    glViewport(0, 0 , w, h);
    glMatrixMode(GL_PROJECTION);
    glPerspective(45.0f, (float)w / (float)h, 0.1f, 100.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();


    main = new Game();
    LOGE("WIDTH x HEIGHT: %dx%d", w, h);
    main->init();
    main->setEngine2dSize(w, h);

    return 0;

}

void drawCube() {
GLfloat vertices[] = {
					//Vertices according to faces
		    		-1.0f, -1.0f, 1.0f, //Vertex 0
		    		1.0f, -1.0f, 1.0f,  //v1
		    		-1.0f, 1.0f, 1.0f,  //v2
		    		1.0f, 1.0f, 1.0f,   //v3

		    		1.0f, -1.0f, 1.0f,	//...
		    		1.0f, -1.0f, -1.0f,
		    		1.0f, 1.0f, 1.0f,
		    		1.0f, 1.0f, -1.0f,

		    		1.0f, -1.0f, -1.0f,
		    		-1.0f, -1.0f, -1.0f,
		    		1.0f, 1.0f, -1.0f,
		    		-1.0f, 1.0f, -1.0f,

		    		-1.0f, -1.0f, -1.0f,
		    		-1.0f, -1.0f, 1.0f,
		    		-1.0f, 1.0f, -1.0f,
		    		-1.0f, 1.0f, 1.0f,

		    		-1.0f, -1.0f, -1.0f,
		    		1.0f, -1.0f, -1.0f,
		    		-1.0f, -1.0f, 1.0f,
		    		1.0f, -1.0f, 1.0f,

		    		-1.0f, 1.0f, 1.0f,
		    		1.0f, 1.0f, 1.0f,
		    		-1.0f, 1.0f, -1.0f,
		    		1.0f, 1.0f, -1.0f,
										};

/** The initial texture coordinates (u, v) */
	GLfloat texture[] = {
		    		//Mapping coordinates for the vertices
		    		0.0f, 0.0f,
		    		0.0f, 1.0f,
		    		1.0f, 0.0f,
		    		1.0f, 1.0f,

		    		0.0f, 0.0f,
		    		0.0f, 1.0f,
		    		1.0f, 0.0f,
		    		1.0f, 1.0f,

		    		0.0f, 0.0f,
		    		0.0f, 1.0f,
		    		1.0f, 0.0f,
		    		1.0f, 1.0f,

		    		0.0f, 0.0f,
		    		0.0f, 1.0f,
		    		1.0f, 0.0f,
		    		1.0f, 1.0f,

		    		0.0f, 0.0f,
		    		0.0f, 1.0f,
		    		1.0f, 0.0f,
		    		1.0f, 1.0f,

		    		0.0f, 0.0f,
		    		0.0f, 1.0f,
		    		1.0f, 0.0f,
		    		1.0f, 1.0f,

		    							};

/** The initial indices definition */
GLbyte indices[] = {
					//Faces definition
		    		0,1,3, 0,3,2, 			//Face front
		    		4,5,7, 4,7,6, 			//Face right
		    		8,9,11, 8,11,10, 		//...
		    		12,13,15, 12,15,14,
		    		16,17,19, 16,19,18,
		    		20,21,23, 20,23,22,
										};
	//Bind our only previously generated texture in this case
	glBindTexture(GL_TEXTURE_2D, cubeTexture->handle);

	//Point to our buffers
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glVertexPointer(3, GL_FLOAT, 0, vertices);
	glTexCoordPointer(2, GL_FLOAT, 0, texture);
	glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, indices);

	//Disable the client state before leaving
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}

void onStart2D() {

	glDisable(GL_DEPTH_TEST);

	//Set up OpenGL projection matrix
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glOrthof(0, main->screenWidth, 0, main->screenHeight, -1, 1);


	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	//Initialize OpenGL states
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glColor4f(0, 0, 0, 1);
	//glClear(GL_COLOR_BUFFER_BIT);
}

void onRun3D(float delta) {

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_TEXTURE_2D);			//Enable Texture Mapping ( NEW )
	glEnable(GL_DEPTH_TEST); 			//Enables Depth Testing
	glViewport(0, 0 , main->screenWidth, main->screenHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glPerspective(45.0f, (float)main->screenWidth / (float)main->screenHeight, 0.1f, 100.0f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

//	main->onRun3D(delta);
	glTranslatef(0.0f, 0.0f, -6.0f);		//Move up 1.3 Units and -6.0 into the Screen
	glScalef(0.6f, 0.6f, 0.6f);
	glRotatef(myAngle, 0.0f, 1.0f, 0.0f);

	drawCube();

//	glTranslatef(0.0f, 0.0f, -4.0f);

//	drawSphere(10, 10, 1.0f, 1.0f, "dummy");

	myAngle += 0.5f;
}

/**
 * Just the current frame in the display.
 */
static void engine_draw_frame(struct engine* engine) {
    if (engine->display == NULL) {
        // No display.
        return;
    }
    const double currentTime 	= Util::getTime();
    float delta = (currentTime - lastTime)/1000.0f;
    lastTime = currentTime;

	if(delta > 0.1f)
		delta	= 0.1f;

//	onRun3D(delta);
//	onStart2D();
//    // Just fill the screen with a color.
//    glClearColor(((float)engine->state.x)/engine->width, engine->state.angle,
//            ((float)engine->state.y)/engine->height, 1);
//    glClear(GL_COLOR_BUFFER_BIT);
//    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//    glEnable(GL_DEPTH_TEST); 			//Enables Depth Testing

//	GLfloat vertices[] = {
//				0.0f,  1.0f,  0.0f, 	//Top
//			   -1.0f, -1.0f,  1.0f, 	//Bottom Left
//				1.0f, -1.0f,  1.0f, 	//Bottom Right
//
//				0.0f,  1.0f,  0.0f,		//Top Of Triangle (Right)
//				1.0f, -1.0f,  1.0f,		//Left Of Triangle (Right)
//				1.0f, -1.0f, -1.0f,		//Right Of Triangle (Right)
//
//				0.0f,  1.0f,  0.0f,		//Top Of Triangle (Back)
//				1.0f, -1.0f, -1.0f,		//Left Of Triangle (Back)
//			   -1.0f, -1.0f, -1.0f,		//Right Of Triangle (Back)
//
//				0.0f,  1.0f,  0.0f,		//Top Of Triangle (Left)
//			   -1.0f, -1.0f, -1.0f,		//Left Of Triangle (Left)
//			   -1.0f, -1.0f,  1.0f		//Right Of Triangle (Left)
//		};
//
//
//	glVertexPointer(3, GL_FLOAT, 0 , vertices);
//	glDrawArrays(GL_TRIANGLE_STRIP, 0, 12);
	onRun3D(delta);
	onStart2D();

	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

//	fontAtlas->renderAtlas(200, test->screenHeight - 200);

    main->run2d(delta);

    batcher.renderCurr();

    eglSwapBuffers(engine->display, engine->surface);
}

/**
 * Tear down the EGL context currently associated with the display.
 */
static void engine_term_display(struct engine* engine) {
    if (engine->display != EGL_NO_DISPLAY) {
        eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        if (engine->context != EGL_NO_CONTEXT) {
            eglDestroyContext(engine->display, engine->context);
        }
        if (engine->surface != EGL_NO_SURFACE) {
            eglDestroySurface(engine->display, engine->surface);
        }
        eglTerminate(engine->display);
    }
    engine->animating = 0;
    engine->display = EGL_NO_DISPLAY;
    engine->context = EGL_NO_CONTEXT;
    engine->surface = EGL_NO_SURFACE;
}

/**
 * Process the next input event.
 */
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
    struct engine* engine = (struct engine*)app->userData;
    if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
//        engine->animating = 1;
        engine->state.x = AMotionEvent_getX(event, 0);
        engine->state.y = AMotionEvent_getY(event, 0);
        return 1;
    }
    return 0;
}

/**
 * Process the next main command.
 */
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
    struct engine* engine = (struct engine*)app->userData;
    switch (cmd) {
        case APP_CMD_SAVE_STATE:
            // The system has asked us to save our current state.  Do so.
            engine->app->savedState = malloc(sizeof(struct saved_state));
            *((struct saved_state*)engine->app->savedState) = engine->state;
            engine->app->savedStateSize = sizeof(struct saved_state);
            break;
        case APP_CMD_INIT_WINDOW:
            // The window is being shown, get it ready.
            if (engine->app->window != NULL) {
                engine_init_display(engine);

               pngAassetManager = app->activity->assetManager;
               asset = AAssetManager_open(pngAassetManager, "nehe.png", AASSET_MODE_UNKNOWN);
               //tex = main->loadPng(pngAassetManager, asset);
//               cubeTexture = resourcesManager.getTexture(asset, "nehe.png");
//               AAsset_close(asset);
               cubeTexture = resourcesManager.getTexture("/sdcard/demo_resources/nehe.png");
               fontFile = AAssetManager_open(pngAassetManager, "LiberationSans-Bold.ttf", AASSET_MODE_BUFFER);

               const void* fontData = AAsset_getBuffer(fontFile);

               off_t fontLen = AAsset_getLength(fontFile);

               initFreeTP(fontData, fontLen);

               scene.createScene("/sdcard/demo_resources/Scene1.ASE");

               engine_draw_frame(engine);
            }
            break;
        case APP_CMD_TERM_WINDOW:
            // The window is being hidden or closed, clean it up.
            engine_term_display(engine);
            break;
        case APP_CMD_GAINED_FOCUS:
            // When our app gains focus, we start monitoring the accelerometer.
            if (engine->accelerometerSensor != NULL) {
                ASensorEventQueue_enableSensor(engine->sensorEventQueue,
                        engine->accelerometerSensor);
                // We'd like to get 60 events per second (in us).
                ASensorEventQueue_setEventRate(engine->sensorEventQueue,
                        engine->accelerometerSensor, (1000L/60)*1000);
            }
            break;
        case APP_CMD_LOST_FOCUS:
            // When our app loses focus, we stop monitoring the accelerometer.
            // This is to avoid consuming battery while not being used.
            if (engine->accelerometerSensor != NULL) {
                ASensorEventQueue_disableSensor(engine->sensorEventQueue,
                        engine->accelerometerSensor);
            }
            // Also stop animating.
            engine->animating = 0;
            engine_draw_frame(engine);
            break;
    }
}

/**
 * This is the main entry point of a native application that is using
 * android_native_app_glue.  It runs in its own thread, with its own
 * event loop for receiving input events and doing other things.
 */
void android_main(struct android_app* state) {
    struct engine engine;

    // Make sure glue isn't stripped.
    app_dummy();

    memset(&engine, 0, sizeof(engine));
    state->userData = &engine;
    state->onAppCmd = engine_handle_cmd;
    state->onInputEvent = engine_handle_input;
    engine.app = state;

    // Prepare to monitor accelerometer
    engine.sensorManager = ASensorManager_getInstance();
    engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
            ASENSOR_TYPE_ACCELEROMETER);
    engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
            state->looper, LOOPER_ID_USER, NULL, NULL);

    if (state->savedState != NULL) {
        // We are starting with a previous saved state; restore from it.
        engine.state = *(struct saved_state*)state->savedState;
    }

    // loop waiting for stuff to do.

    while (1) {
        // Read all pending events.
        int ident;
        int events;
        struct android_poll_source* source;

        // If not animating, we will block forever waiting for events.
        // If animating, we loop until all events are read, then continue
        // to draw the next frame of animation.
        while ((ident=ALooper_pollAll(engine.animating == 0, NULL, &events,
                (void**)&source)) >= 0) {

            // Process this event.
            if (source != NULL) {
                source->process(state, source);
            }

            // If a sensor has data, process it now.
            if (ident == LOOPER_ID_USER) {
                if (engine.accelerometerSensor != NULL) {
                    ASensorEvent event;
                    while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
                            &event, 1) > 0) {
//                        LOGI("accelerometer: x=%f y=%f z=%f",
//                                event.acceleration.x, event.acceleration.y,
//                                event.acceleration.z);
                    }
                }
            }

            // Check if we are exiting.
            if (state->destroyRequested != 0) {
                engine_term_display(&engine);
                return;
            }
        }

        if (engine.animating == 0) {
            // Done with events; draw next animation frame.
            engine.state.angle += .01f;
            if (engine.state.angle > 1) {
                engine.state.angle = 0;
            }

            // Drawing is throttled to the screen update rate, so there
            // is no need to do timing here.
            engine_draw_frame(&engine);
        }
    }
}
//END_INCLUDE(all)
